class ForumsController < ApplicationController
  
  before_filter :set_current_menu_and_title
  
  def index
    @forums = Forum.find(:all, :order => "sequence asc")
    @forums.each do |f|
      p = Post.find_by_forum_id(f.id, :order => "created_at desc")
      f.last_post = p
    end
    @rss_forums = Post.find(:all, :limit => 10, :order => 'created_at desc')
  end

  def show
    @forum = Forum.find(params[:id])
    @posts = Post.paginate_by_forum_id(@forum.id, :per_page => 10, :page => params[:page], :order => 'created_at desc')
    @posts.each do |p|
      comments = Comment.find_all_by_post_id(p.id, :order => "created_at desc")
      if comments.size == 0
        user = p.user
      else
        user = comments.first.user
      end
      p.last_user = user
    end
  end

  def new
    @forum = Forum.new
  end

  def edit
    @forum = Forum.find(params[:id])
  end

  def create
    @forum = Forum.new(params[:forum])

    respond_to do |format|
      if @forum.save
        flash[:notice] = 'Forum was successfully created.'
        format.html { redirect_to(@forum) }
        format.xml  { render :xml => @forum, :status => :created, :location => @forum }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @forum.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @forum = Forum.find(params[:id])

    respond_to do |format|
      if @forum.update_attributes(params[:forum])
        flash[:notice] = 'Forum was successfully updated.'
        format.html { redirect_to(@forum) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @forum.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @forum = Forum.find(params[:id])
    @forum.destroy

    respond_to do |format|
      format.html { redirect_to(forums_url) }
      format.xml  { head :ok }
    end
  end
  
  private
    def set_current_menu_and_title
      @current_menu = :forum
      @title = "论坛"
    end
end
